package org.jash.document.model

import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import org.jash.common.log.logDebug
import org.jash.common.mvi.BaseState
import org.jash.common.mvi.BaseViewModel
import org.jash.common.net.retrofit
import org.jash.document.net.DocService

class DocViewModel:BaseViewModel<DocIntent, DocState>() {
    val service by lazy { retrofit.create(DocService::class.java) }
    fun selDoc(sel:DocIntent.SelDocuments) {
        viewModelScope.launch {
            state.value = try {
                val res = service.selDocuments(mapOf("userId" to sel.userId, "page" to sel.page))
                if (res.statusCode == 200) {
                    DocState.Documents(res.data)
                } else {
                    BaseState.Error(res.msg)
                }
            } catch (e:Exception) {
                BaseState.Error(e.message ?: "")
            }
        }

    }
    fun delDoc(del:DocIntent.DelDocuments) {
        viewModelScope.launch {
            state.value = try {
                val res = service.delDocuments(mapOf("FileId" to del.fileId))
                if (res.statusCode == 200) {
                    DocState.Delete(del.fileId)
                } else {
                    BaseState.Error(res.msg)
                }
            } catch (e:Exception) {
                BaseState.Error(e.message ?: "")
            }
        }
    }
}